<template lang="pug">
  .checkout-dialog
    el-dialog(
      :title="payFlag ? '完成支付' : '结账付款' ",
      top="5vh",
      width="900px",
      :visible.sync="showModal",
      :before-close="beforeCloseHandler")

      .content(
        v-if='!payFlag',
        v-loading="loading"
        element-loading-text="订单创建中……"
        element-loading-spinner="el-icon-loading")

        .pay-method
          h3 支付方式
          el-radio-group.mt20(v-model="payment")
            el-radio(:label="3") 余额
            el-radio(:label="1") 支付宝
            el-radio(:label="2") 微信

        .addr-list.clearfix(v-if="getAddressList")
          el-collapse(v-model="activeNames")
            el-collapse-item(title="收货地址", name="1")
              .addr-item.fl.pos-r(
                v-for="(addr, index) in getAddressList",
                :class="{'active': addressCur == index}",
                :key="addr.addressid")
                .addr-conten(@click="useAddress(index)")
                  .addr-name 姓名：{{addr.name}}
                  .addr-address 地址: {{addr.province}} {{addr.address}}
                  .addr-phone 手机: {{addr.mobile}}
                .addr-ctrl.tac
                  span(@click="editorAddr(addr)") 修改
                  span(@click="deleteAddr(addr)") 删除
              .addr-item.addr-add-new.tac(@click="addNewAddr")
                span.mt20
                  i.iconfont.icon-plus
                p 使用新地址

            el-collapse-item(title="显示更多", name="2", v-if="addressList.length > 2")
              .addr-list.clearfix
                .addr-item.tac.pos-r.fl(
                  :class="{'active': addressCur == index}",
                  v-for="(addr, index) in addressList",
                  :key="addr.addressid")
                  .addr-conten(@click="useAddress(index)")
                    .addr-name 姓名：{{addr.name}}
                    .addr-address 地址: {{addr.province}} {{addr.address}}
                    .addr-phone 手机: {{addr.mobile}}
                  .addr-ctrl.tac
                    span(@click="editorAddr(addr)") 修改
                    span(@click="deleteAddr(addr)") 删除

        table(v-if="cartList")
          colgroup
            col(class="name-col")
            col(class="price-col")
            col(class="price-col")
            col(class="amount-col")
            col(class="total-col")
          thead
            tr
              th.name 商品信息
              th
              th.price 价格
              th.amount 数量
              th.total 总价
          tbody
            tr(v-for="goods in cartList", :key="goods.productid")
              td
                .name.clearfix
                  .thumb.fl
                    img(:src="goods.productimgs[0].thumburl")
                  .name-table.fl.tal
                    .title.omit2 {{goods.name}}
              td
              td
                .price ￥ {{goods.price}}
              td
                .num {{goods.num}}
              td
                .subtotal {{Math.round(parseFloat(goods.price * goods.num) * 100)/100}}
        .pay-info.tar
          span 应付总额：
            strong.pay-money ￥ {{Number(totalMoney).toFixed(2) }}
          el-button(type="primary", @click="handleCheckout") 立即付款

      .content.tac(v-else)
        .pay-succ-icon
          i.iconfont.icon-roundcheck
        .pay-succ-info
          h2 支付完成
          p 您可以在
            a(href='', @click.stop.prevent='showOrderList') &nbsp; 我的订单 &nbsp;
            | 中查看该订单信息
          p 该窗口将在
            strong {{closeTime}}s
            | 后自动关闭
</template>

<script>
import { mapGetters } from 'vuex'
import { isWxBrowser } from '@/utils'
import modalMixin from '@/mixins/modal'
let payBtn = true
export default {
  name: 'checkoutModal',
  mixins: [modalMixin],
  data() {
    return {
      loading: false,
      cartList: null,
      payment: 3,
      activeNames: ['2'],
      addressCur: 0,
      totalMoney: 0,
      payFlag: false,
      closeTime: 10,
      timer: null
    }
  },
  mounted() {
    // 从购物车页面过来结算
    this.getCheckoutInfo()

    // 创建订单失败
    this.createOrderFailed()

    // 支付成功
    this.paySuccess()

    // 支付失败
    this.payFailed()
  },
  computed: {
    ...mapGetters(['addressList', 'userBalance', 'userInfo']),
    getAddressList() {
      if(this.addressList) {
        return this.addressList.slice(0, 2)
      }
    },
    formatAddr() {
      return this.addressList.slice(0, 2)
    }
  },
  methods: {
    getCheckoutInfo() {
      this.$vgo.on('checkout', (data) => {
        this.openModal()
        this.payFlag = false
        this.cartList = []
        this.cartList = data.goods
        this.totalMoney = data.money

        this.$nextTick(() => {
          setTimeout(() => {
            this.activeNames =  ['1']
          }, 1000)
        })

        if(!this.addressList) {
          this.getUserAddresses()
        }
        if(!this.userBalance) {
          this.$store.dispatch('getUserBalance', this.totalMoney)
        }
      })
    },
    createOrderFailed() {
      this.$vgo.on('createorder:failed', () => {
        this.loading = false
        this.closeModal()
      })
    },
    paySuccess() {
      this.$vgo.on('pay:success', data => {
        // 非余额付款
        if(data.data) {
          const openid = this.userInfo ? this.userInfo.wx_openid : ''
          const url = data.data + '&pano_id='+ this.$route.params.panoId +'&openid=' + openid

          window.location.href = url
        } else {
          this.$vgo.tip('支付成功', 'success', 2000)
        }

        if(this.payment == 3) {
          // 倒计时关闭弹窗
          this.countDown()
        }
        this.loading = false
        this.payFlag = true
      })
    },
    payFailed() {
      this.$vgo.on('pay:failed', () => {
        //this.$vgo.tip('网络异常，支付失败！', 'error', 2000)
        setTimeout(() => {
          this.loading = false
          this.payFlag = false
        }, 2000)
      })
    },
    getUserAddresses() {
      if(!this.addressList) {
        this.$store.dispatch('fetchUserAddress')
      }
    },
    useAddress(index){
      this.addressCur = index
    },
    editorAddr(addrItem) {
      this.$vgo.emit('address:editor', addrItem)
    },
    deleteAddr(addr) {
      this.$vgo.open(() => {
        this.$store.dispatch('delAddress', addr.addressid)
      })
    },
    addNewAddr() {
      this.$vgo.emit('model:address')
    },
    showOrderList() {
      this.$vgo.emit('order:usercenter')
      this.beforeCloseHandler()
    },
    handleCheckout() {
      if(!payBtn) return
      payBtn = false

      if (this.payment == 3) {
        if(this.userBalance && this.userBalance < this.totalMoney) {
          this.$vgo.tip('您的账户余额不足，请先充值！', 'warning')
          return
        }
      }
      this.loading = true
      this.pay()
    },
    pay() {
      let cartidStr = []

      this.cartList.map(item => {
        cartidStr.push(item.cartid)
      })
      cartidStr = "[" + cartidStr.join(',') + '' + "]"

      this.$store.dispatch('createOrder',
        {
          cartIds: cartidStr,
          address: this.addressList[this.addressCur].addressid,
          money: this.totalMoney,
          payment: Number(this.payment),
          url: $globalconfig.URLS.PANO_VIEW_PREFIX + this.$route.params.panoId,
          iswx: isWxBrowser() ? 'true' : 'false'
        })
    },
    countDown() {
      this.timer = setTimeout(() => {
        this.closeTime--
        if(this.closeTime > 0) {
          this.countDown()
        } else {
          this.closeModal()
          this.closeTime = 10
          clearTimeout(this.timer)
        }
      }, 1000)
    },
    beforeCloseHandler() {
      clearTimeout(this.timer)
      this.closeModal()
      setTimeout(() => {
        this.closeTime = 10
      }, 1000)
    }
  }
}
</script>
<style lang="stylus">
$borderColor = #e1e1e1
$blue = #20A0FF
$success = #13CE66
.checkout-dialog
  .el-dialog__body
    padding: 20px
  .pay-method
    margin-bottom: 20px
  .addr-more
    margin: 20px 0
  .addr-list
    .addr-item
      width: 32%
      height: 140px
      padding: 20px
      margin-bottom: 10px
      box-sizing: border-box
      border: 1px solid $borderColor
      border-radius: 4px
      overflow: hidden
      cursor: pointer
      &:not(last-child)
        margin-right: 10px
      &:hover
        .addr-ctrl
          transform: translate3d(0, 0, 0)
      &.active
        border-color: $blue
      .addr-ctrl
        position: absolute
        left: 0
        bottom: 0
        width: 100%
        border-top: 1px solid $borderColor
        transform: translate3d(0, 100%, 0)
        transition: all .6s
        & > span
          display: inline-block
          width: 50%
          line-height: 30px
          box-sizing: border-box
          cursor: pointer
          &:first-child
            border-right: 1px solid $borderColor
          &:hover
            background: $borderColor
  .pay-info
    button
      margin-left: 20px
    .pay-money
      font-size: 30px
      color: $danger
  .pay-succ-icon
    padding: 30px 0
    i
      font-size: 120px
      color: $success
  .pay-succ-info
    h2
      font-size: 20px
      font-weight: 700
    p
      padding: 10px
    a
      color: $blue
  table
    thead
      tr
        .name
          padding-left: 20px
        .title
          padding-left: 10px
</style>
